﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Net;
using System.IO;
using System.Text;
using common;
using System.Collections.Generic;
using System.Xml;

namespace common.web
{
    public class pg
    {

        #region 根据字符串长度截断
        /// <summary>
        /// 根据字符串长度截断
        /// </summary>
        /// <param name="s"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string StringLengthFormat(string s, int len)
        {
            if (len <= 0 || s.Length <= len)
            {
                return s;
            }
            else
            {
                return s.Substring(0, len) + "...";
            }
        }
        #endregion

        public static string usid()
        {
            string _usid = "0";
            string _us = func.safeStr(func.base64De(func.getCookis("zsk05")));
            string _pa = func.getCookis("zsk06");
            if (_us == "" || _pa == "")
            { }
            else
            {
                DataTable dt = db.dtTable("select id,cPwd from t_Users where cUser='" + _us + "'");
                if (dt.Rows.Count == 1 && dt.Rows[0]["cPwd"].ToString() == _pa) _usid = dt.Rows[0]["id"].ToString();
            }
            return _usid;
        }
        public static string czusid()
        {
            string _usid = "0";
            string czuid = func.getCookis("cz01");
            if (czuid != "")
            {
                _usid = new KeyPwd().Decrypto(czuid);
                if (_usid.Contains("|")) _usid = _usid.Split('|')[0];
            }
            return _usid;
        }

        public static string idchk()
        {
            string _usid = usid();
            if (_usid == "0")
            {
                func.cleCookis("a07");
                //func.Alert("您没有登录,需要先登录!", "https://www.wsloan.com/login.aspx");
                func.Alert("您没有登录,需要先登录!", "/login.aspx?act=exit&t=1");
            }
            else
            {
                //HttpCookie hc = HttpContext.Current.Request.Cookies["a08"];
                //hc.Expires = DateTime.Now.AddMinutes(15.0);
                //HttpContext.Current.Response.Cookies.Add(hc);
                HttpContext.Current.Response.Cookies["c"].Value = _usid;
            }
            return _usid;
        }
        //判断是否登录
        public static string idchk1()
        {
            string _usid = usid();
            if (_usid != "0")
            {
                //HttpCookie hc = HttpContext.Current.Request.Cookies["a08"];
                //hc.Expires = DateTime.Now.AddMinutes(15.0);
                //HttpContext.Current.Response.Cookies.Add(hc);
                HttpContext.Current.Response.Cookies["c"].Value = _usid;
            }
            return _usid;
        }
        public static string idchkm()
        {
            string _usid = usid();
            if (_usid == "0")
            {
                func.cleCookis("a07");
                func.Alert("您没有登录,需要先登录!", "login.aspx");
            }
            else
            {
                //HttpCookie hc = HttpContext.Current.Request.Cookies["a08"];
                //hc.Expires = DateTime.Now.AddMinutes(15.0);
                //HttpContext.Current.Response.Cookies.Add(hc);
                HttpContext.Current.Response.Cookies["c"].Value = _usid;
            }
            return _usid;
        }

        public static string[] zhye(string _uid, string sql)
        {
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@uid", SqlDbType.Int);
            param[0].Value = _uid;
            param[1] = new SqlParameter("@sql", SqlDbType.NVarChar, 800);
            param[1].Value = sql;

            DataTable dt = db.dtTable("yhye", "c", param);
            string[] jg = { "0", "0", "0", "0", "0" };
            jg[0] = dt.Rows[0]["fSjje"].ToString();
            jg[1] = dt.Rows[0]["fDjje"].ToString();
            jg[2] = dt.Rows[0]["fDsje"].ToString();
            jg[3] = dt.Rows[0]["ze"].ToString();
            if (decimal.Parse(jg[2]) < 0)
            {
                jg[3] = (decimal.Parse(jg[3]) - decimal.Parse(jg[2])).ToString();
                jg[2] = "0";
            }
            jg[4] = dt.Rows[0]["cs"].ToString();
            return jg;
        }

        public static void addjfjl(string _uid, string bdlx, string sm, string _hyf, string _xyf, string _bs)  //积分记录
        {
            db.ExecNQ("insert into t_Jfjl (fUid,fJclx,cBdsm,fBdjf,fXyjf,tDate,cBs) values (" + _uid + "," + bdlx + ",'" + sm + "'," + _hyf + "," + _xyf + ",'" + DateTime.Now.ToString() + "','" + _bs + "')");
        }

        public static void addjfjl1(string _uid, string bdlx, string sm, string _hyf, string _xyf, string _bs, string _bs1)  //积分记录
        {
            db.ExecNQ("insert into t_Jfjl (fUid,fJclx,cBdsm,fBdjf,fXyjf,tDate,cBs,cBs1) values (" + _uid + "," + bdlx + ",'" + sm + "'," + _hyf + "," + _xyf + ",'" + DateTime.Now.ToString() + "','" + _bs + "','" + _bs1 + "')");
        }

        public static void addzjjl(string _uid, string bdlx, string sm, string _bdje, string _rzje, string _xmlx, string _dyid, string _kyye, string _djye, string _dsje, string _zhze, string sm1)  //资金记录
        {
            db.ExecNQ("insert into t_Zjjl (fUid,fJclx,cBdsm,fBdje,fRzje,cXmlx,tDate,fDyid,fKyye,fDjje,fDsje,fZhze,cSm) values (" + _uid + "," + bdlx + ",'" + sm + "'," + _bdje + "," + _rzje + ",'" + _xmlx + "','" + DateTime.Now.ToString() + "'," + _dyid + "," + _kyye + "," + _djye + "," + _dsje + "," + _zhze + ",'" + sm1 + "')");
        }

        public static string addzjjl1(string _uid, string bdlx, string sm, string _bdje, string _rzje, string _xmlx, string _dyid, string _kyye, string _djye, string _dsje, string _zhze, string sm1)  //资金记录
        {
            string str = "";
            str = db.ExecNid("insert into t_Zjjl (fUid,fJclx,cBdsm,fBdje,fRzje,cXmlx,tDate,fDyid,fKyye,fDjje,fDsje,fZhze,cSm) values (" + _uid + "," + bdlx + ",'" + sm + "'," + _bdje + "," + _rzje + ",'" + _xmlx + "','" + DateTime.Now.ToString() + "'," + _dyid + "," + _kyye + "," + _djye + "," + _dsje + "," + _zhze + ",'" + sm1 + "')");
            return str;
        }

        public static void czjfjl(string _uid, string bdlx, string sm, string _hyf)  //积分记录
        {
            db.ExecNQ("insert into t_czJfjl (fUid,fJclx,cBdsm,fBdjf,tDate) values (" + _uid + "," + bdlx + ",'" + sm + "'," + _hyf + ",'" + DateTime.Now.ToString() + "')");
        }

        public static void chkzfmm(string mm, string inp)
        {
            if (inp == "") func.Alert("温商贷交易密码不能为空!", null);
            if (mm == "" || func.PassStr(inp, "MD5") != mm)
            {
                func.Alert("温商贷交易密码不正确!", null);
            }
        }

        public static bool zfmmyz(string inppas, string dbpas)
        {
            if (inppas == "") return false;
            if (dbpas == "" || func.PassStr(inppas, "MD5") != dbpas) return false;
            return true;
        }

        public static void zfmmchk(string inppas, string dbpas)
        {
            if (!zfmmyz(inppas, dbpas)) func.Alert("交易密码不正确!", null);
        }

        public static string xsz(string s, string ts)
        {
            s = func.NoNull(s).Trim();
            if (func.chkRegex(s, @"^\d{1,9}(\.\d{1,2})?$") == false) func.Alert(ts + "必须为数字格式!", null);
            if (Convert.ToDouble(s) <= 0) func.Alert(ts + "金额不能为0!", null);
            return s;
        }

        #region 计算提现手续费
        public static decimal GetFreeMoney(string uid)
        {
            decimal mfed = 0;
            decimal fmfed = 0;
            string zjjlid = "";
            decimal fKyye = 0;
            string str = " and fuid=" + uid;
            string str1 = "and fuid=" + uid;
            string firstID = "";
            string exZjjlid = db.ExecOne("select fZjjlId from t_mfed where fuid=" + uid);
            if (string.IsNullOrEmpty(exZjjlid))
            {
                string drje = db.ExecOne("select top 1 fbdje from ws_db2.dbo.t_zjjl1 where cxmlx='初次导入' and fuid=" + uid);
                if (!string.IsNullOrEmpty(drje))
                {
                    decimal fdrje = Convert.ToDecimal(drje);
                    if (fdrje > 0)
                        firstID = db.ExecOne("select top 1 id from ws_db2.dbo.t_zjjl1 where cxmlx='初次导入' and fuid=" + uid);
                }
                if (string.IsNullOrEmpty(firstID))
                    firstID = db.ExecOne(string.Format("select top 1 id FROM (SELECT (id+3129939) id FROM t_zjjl where fuid={0} UNION ALL SELECT id FROM  ws_db2.dbo.t_zjjl1 where fuid={0}) t order by id", uid));
                if (!string.IsNullOrEmpty(firstID))
                {
                    str += " and id>=" + firstID;
                    str1 += " and (id+3129939)>=" + firstID;
                }
            }
            else
            {
                DataTable dted = db.dtTable("select fmfed,ffmfed from t_mfed where fuid=" + uid);
                if (dted.Rows.Count > 0)
                {
                    mfed = Convert.ToDecimal(dted.Rows[0]["fmfed"]);
                    fmfed = Convert.ToDecimal(dted.Rows[0]["ffmfed"]);
                }
                str += " and id>" + exZjjlid;
                str1 += " and (id+3129939)>" + exZjjlid;
            }


            int n = 0;
            DataTable dt = db.dtTable(string.Format(@"SELECT id,id2,fbdje,cxmlx,fKyye,fdyid,cBdsm FROM (select (id+3129939) id,id id2,fbdje,cxmlx,fKyye,fdyid,cBdsm from t_zjjl WHERE cxmlx in 
                ('回款','初次导入','提现冻结','取消提现','投标','撤标','线下充值','利息管理费','投标奖励','重复还款撤回','申请VIP','借款成功','借款手续费','加入理财计划','理财回款','A计划佣金','A计划奖励','投资奖励','推荐奖励','活期转出到余额','余额转入到活期','在线充值','活期收益','发标冻结','返还冻结款','预约冻结','活期手续费','红包扣除','回款续投','奖励扣除','扣除体验金','多打款扣回','微信奖励','退出计划','理财计划','手动撤标','在线充值手续费','取消预约','活动奖励','体验金收益','社区转入','分期冻结','借款成功（信用借款）','投标（信用借款）','还款（信用借款）','回款（信用借款）') 
                AND cbdsm<>'用户提交,后台审核'{1} UNION ALL 
                select id,id id2,fbdje,cxmlx,fKyye,fdyid,cBdsm from ws_db2.dbo.t_zjjl1 WHERE cxmlx in 
                ('回款','初次导入','提现冻结','取消提现','投标','撤标','线下充值','利息管理费','投标奖励','重复还款撤回','申请VIP','借款成功','借款手续费','加入理财计划','理财回款','A计划佣金','A计划奖励','投资奖励','推荐奖励','活期转出到余额','余额转入到活期','在线充值','发标冻结','返还冻结款','预约冻结','红包扣除','回款续投','奖励扣除','扣除体验金','多打款扣回','微信奖励','退出计划','理财计划','手动撤标','在线充值手续费','活动奖励','体验金收益','社区转入','分期冻结') 
                AND cbdsm<>'用户提交,后台审核'{0})t ORDER by id", str, str1));
            foreach (DataRow dr in dt.Rows)
            {
                string cxmlx = dr["cxmlx"].ToString();
                string id = dr["id"].ToString();
                string fdyid = dr["fdyid"].ToString();
                decimal fbdje = Convert.ToDecimal(dr["fbdje"].ToString());
                string cBdsm = dr["cBdsm"].ToString();
                zjjlid = id;
                if (cxmlx == "在线充值")
                {
                    fmfed += fbdje;
                }
                else if (cxmlx == "投标" || cxmlx == "投标（信用借款）" || cxmlx == "余额转入到活期" || cxmlx == "申请VIP" || cxmlx == "加入理财计划" || cxmlx == "发标冻结" || cxmlx == "预约冻结" || cxmlx == "加入理财计划" || cxmlx == "理财计划" || cxmlx == "在线充值手续费" || cxmlx == "分期冻结" || cxmlx == "还款（信用借款）")
                {
                    //先使用非免费提现的余额
                    if (fmfed > 0)
                    {
                        fmfed -= fbdje;
                        if (fmfed < 0)
                        {
                            mfed += fmfed;
                            if (mfed < 0) mfed = 0;
                            fmfed = 0;
                        }
                    }
                    else
                    {
                        mfed -= fbdje;
                        if (mfed < 0) mfed = 0;
                    }
                }
                else if (cxmlx == "取消提现")
                {
                    if (!string.IsNullOrEmpty(fdyid) && fdyid != "0")
                    {
                        DataTable dtxx = db.dtTable("select fmfed,ffmfed from t_tx_xx where ftxjlid=" + fdyid);
                        if (dtxx.Rows.Count > 0)
                        {
                            mfed += Convert.ToDecimal(dtxx.Rows[0]["fmfed"]);
                            fmfed += Convert.ToDecimal(dtxx.Rows[0]["ffmfed"]);
                        }
                        else
                            mfed += fbdje;
                    }
                    else
                    {
                        mfed += fbdje;
                    }
                }
                else
                {
                    if (cxmlx == "回款" || cxmlx == "回款（信用借款）" || cxmlx == "初次导入" || cxmlx == "取消预约" || cxmlx == "撤标" || cxmlx == "线下充值" || cxmlx == "投标奖励" || cxmlx == "借款成功" || cxmlx == "借款成功（信用借款）" || cxmlx == "理财回款" || cxmlx == "A计划佣金" || cxmlx == "A计划奖励" || cxmlx == "投资奖励" || cxmlx == "推荐奖励" || cxmlx == "活期转出到余额" || cxmlx == "活期收益" || cxmlx == "返还冻结款" || cxmlx == "微信奖励" || cxmlx == "退出计划" || cxmlx == "回款续投" || cxmlx == "手动撤标" || cxmlx == "活动奖励" || cxmlx == "体验金收益" || cxmlx == "社区转入")
                    {
                        if (cxmlx == "活期转出到余额" && cBdsm.StartsWith("活期手续费"))
                        {
                            decimal hqsxf = 0;
                            decimal.TryParse(cBdsm.Replace("活期手续费", "").Replace("元", ""), out hqsxf);
                            if (hqsxf > 0)
                                fbdje -= hqsxf;
                        }
                        mfed += fbdje;
                    }
                    else
                    {
                        if (cxmlx == "提现冻结" && cBdsm.StartsWith("财智"))
                            continue;
                        mfed -= fbdje;
                        if (mfed < 0 && fmfed > 0)
                        {
                            fmfed += mfed;
                            mfed = 0;
                        }
                    }
                }
                n++;
            }
            decimal r = mfed;

            if (string.IsNullOrEmpty(exZjjlid))
            {
                if (string.IsNullOrEmpty(zjjlid))
                    zjjlid = "0";
                db.ExecNQ("insert into t_mfed(fuid,fmfed,ffmfed,fsjje,fZjjlId) values(" + uid + "," + mfed + "," + fmfed + "," + fKyye + "," + zjjlid + ")");
            }
            else if (exZjjlid != zjjlid && zjjlid != "")
                db.ExecNQ("update t_mfed set fmfed=" + mfed + ",ffmfed=" + fmfed + ",fsjje=" + fKyye + ",fZjjlId=" + zjjlid + " where fuid=" + uid);

            //<!--
            //判断该用户是否有单笔投资大于或等于1000的记录
            int hasTZ = db.ExecInt("select count(id) from t_Tzjl where fTze>=1000 and fuid=" + uid);
            //当没有这样的记录时，才去改变可用余额
            if (hasTZ == 0)
            {
                //得到体验金活动产生的利息
                decimal tyjLX = Convert.ToDecimal(db.ExecNumb("select sum(fCzje) from t_Czjl where fuid=" + uid + " and cZffs='其它：3.0版体验金利息' and fZt=1 and fRzlx=2"));
                if (r >= tyjLX)
                {
                    r = r - tyjLX;
                }
            }
            //-->
            if (fmfed > 0 && fmfed <= 2)
                r += fmfed;
            decimal fsjje = Convert.ToDecimal(db.ExecNumb("select fsjje from t_user where id=" + uid));
            if (fsjje < r)
                r = fsjje;
            return r;
        }

        public static Dictionary<string, string> txjs(decimal _txe, decimal _ye1, string _uid1)
        {
            decimal mfed = 0, fmfed = 0;

            decimal mf, ytxe = _txe;
            mf = GetFreeMoney(_uid1);

            if (mf > _txe)
            {
                mfed = _txe;
                fmfed = 0;
            }
            else
            {
                mfed = mf;
                fmfed = _txe - mf;
            }

            _txe = _txe - mf;
            if (_txe < 0) _txe = 0;

            decimal sxf = 0; string ms = "";
            if (_txe > 0)
            {
                sxf = _txe * 0.003m; sxf = Math.Round(sxf, 2);
                if (sxf < 1)
                    sxf = 1;
                ms = _txe + "元的手续费" + sxf + "元";
            }
            if (mf > 0)
            {
                if (!string.IsNullOrEmpty(ms))
                    ms += ",";
                ms += mf + "元的免费提现";
            }


            Dictionary<string, string> jg = new Dictionary<string, string>(4);
            jg.Add("sjdz", (ytxe - sxf).ToString());
            jg.Add("sxf", sxf.ToString());
            jg.Add("ms", ms);
            jg.Add("mfed", mfed.ToString());
            jg.Add("fmfed", fmfed.ToString());
            return jg;
        }
        private static txzc gettx(List<txzc> ts, string dyid)
        {
            if (dyid == "0")
                return null;
            foreach (txzc item in ts)
            {
                if (item.Dyid == dyid)
                    return item;
            }
            return null;
        }
        #endregion

        #region 计算回款续投奖励额
        public static decimal getContinueBonus(string uid, string tdate, out txzc xx)
        {

            int day = 6;
            decimal ye = Convert.ToDecimal(db.ExecNumb("SELECT top 1 fkyye FROM [t_Zjjl] where fuid=" + uid + " and datediff(d,tdate,'" + tdate + "')>=" + day + " order by tdate desc,id desc"));

            DataTable dt = db.dtTable("select * from  t_zjjl where fuid=" + uid + " and datediff(d,tdate,'" + tdate + "')<" + day + " and tdate<'" + tdate + "' order by tdate,id");

            decimal hkje = 0, czje = 0;
            List<txzc> txs = new List<txzc>();
            foreach (DataRow dr in dt.Rows)
            {
                string ctype = dr["cxmlx"].ToString();
                decimal rje = decimal.Parse(dr["fBdje"].ToString());
                string fjcix = dr["fJclx"].ToString();
                string cbdsm = dr["cbdsm"].ToString();
                string fDyid = dr["fDyid"].ToString();
                decimal fHkje = 0;
                decimal.TryParse(dr["fHkje"].ToString(), out fHkje);

                if (ctype.Contains("提现成功") || ctype == "扣除冻结款" || ctype == "扣除冻结款" || cbdsm.Contains("理财"))
                    continue;

                if (ctype == "回款")
                    hkje += rje;
                else if (ctype == "提现冻结")
                {
                    //if (fHkje != 0 && fHkje != hkje)
                    //{
                    //    ye -= (fHkje - hkje);
                    //    hkje = fHkje;
                    //}
                    txzc tx = new txzc();
                    tx.Dyid = fDyid;

                    if (ye < rje)
                    {
                        rje -= ye;
                        tx.Ye = ye;
                        ye = 0;
                        if (rje > hkje)
                        {
                            tx.Hkje = hkje;
                            tx.Czje = (rje - hkje);
                            czje -= (rje - hkje);
                            hkje = 0;
                        }
                        else
                        {
                            hkje -= rje;
                            tx.Hkje = rje;
                        }
                    }
                    else
                    {
                        ye -= rje;
                        tx.Ye = rje;
                    }

                    txs.Add(tx);
                }
                else
                {
                    if (fjcix == "1")
                    {
                        if (ctype == "取消提现")
                        {
                            txzc tx = gettx(txs, fDyid);
                            if (tx != null)
                            {
                                hkje += tx.Hkje;
                                czje += tx.Czje;
                                ye += tx.Ye;
                            }
                            else
                                ye += rje;
                        }
                        else if (ctype == "投标奖励" || cbdsm.Contains("手工") || cbdsm.Contains("自动") || ctype.Contains("奖励"))
                            ye += rje;
                        else
                        {
                            //if (ctype == "在线充值" || ctype == "线下充值")
                            czje += rje;
                            //else
                            //    ye += rje;
                        }
                    }
                    else
                    {
                        if (cbdsm == "投标冻结资金")
                        {
                            //if (fHkje != 0 && fHkje != hkje)
                            //{
                            //    ye -= (fHkje - hkje);
                            //    hkje = fHkje;
                            //}
                            if (rje > hkje)
                            {
                                rje -= hkje;
                                hkje = 0;
                                if (rje > czje)
                                {
                                    ye -= (rje - czje);
                                    czje = 0;
                                }
                                else
                                    czje -= rje;
                            }
                            else
                                hkje -= rje;
                        }
                        else if (ctype == "利息管理费")
                        {
                            hkje -= rje;
                        }
                        else
                        {
                            if (rje > czje)
                            {
                                rje -= czje;
                                czje = 0;
                                if (rje > ye)
                                {
                                    hkje -= (rje - ye);
                                    ye = 0;
                                }
                                else
                                    ye -= rje;
                            }
                            else
                                czje -= rje;
                        }
                    }

                }
            }
            xx = new txzc();
            xx.Czje = czje;
            xx.Hkje = hkje;
            xx.Ye = ye;
            return hkje;
        }

        /// <summary>
        /// 添加回款续投奖励
        /// </summary>
        /// <param name="zjjlid"></param>
        /// <param name="cUser"></param>
        public static void addxt(string zjjlid, string bid)
        {
            //取消回款续投 2014-02-10
            //using (IDataReader dr = db.dtReader("select fUid,tdate,fBdje,fDyid from t_zjjl where id=" + zjjlid))
            //{
            //    if (dr.Read())
            //    {
            //        string uid = dr["fuid"].ToString();
            //        string fDyid = dr["fDyid"].ToString();
            //        string tDate = dr["tdate"].ToString();
            //        decimal tze = decimal.Parse(dr["fBdje"].ToString());
            //        txzc xx = new txzc();
            //        decimal xtje = pg.getContinueBonus(uid, tDate, out xx);
            //        decimal _je = 0;
            //        if (tze > xtje)
            //            _je = xtje;
            //        else
            //            _je = tze;
            //        double je1 = 0;
            //        je1 = Math.Round(Convert.ToDouble(_je) * 0.0015, 2);
            //        if (je1 > 0)
            //        {
            //            db.ExecNQ("insert into t_xt(fUid,fTzjlID,fBid,ftze,fxtje,fjl) values(" + uid + "," + zjjlid + "," + bid + "," + tze + "," + _je + "," + je1 + ")");
            //            db.ExecNQ("update t_zjjl set fHkje=" + xx.Hkje + " where id=" + zjjlid);
            //        }
            //    }
            //}
        }
        #endregion

        public static void czpx(string uid, decimal ye, decimal bdje)  //充值排序
        {
            decimal ye_o = ye - bdje;
            int ct_z = db.ExecInt("select count(id) from t_Zdtb where fIskg=1 and fuid=" + uid);
            if (ct_z > 0)
            {
                decimal zdje = Convert.ToDecimal(db.ExecNumb("select fzdje from t_Zdtb where fIskg=1 and fuid=" + uid));
                if (ye_o - zdje < 50 && ye - zdje >= 50)
                {
                    ct_z = db.ExecInt("select max(id) from t_Tbpx");
                    db.ExecNQ("update t_Tbpx set id=" + (ct_z + 1) + " where fuid=" + uid);
                }
            }
        }
        /// <summary>
        /// 是否加入值班池,True为直接加入值班池
        /// </summary>
        /// <returns></returns>
        public static bool IsZhiBanChi()
        {
            string sDate = "2015-10-01,2015-10-02,2015-10-03,2015-10-04,2015-10-05,2015-10-06";
            bool isbujia = false;
            if (sDate.Contains(","))
            {
                string[] arr = sDate.Split(',');
                for (int i = 0; i < arr.Length; i++)
                {
                    if (DateTime.Now.Date == Convert.ToDateTime(arr[i]))
                    {
                        isbujia = true;
                        break;
                    }
                }
            }
            else
            {
                if (DateTime.Now.Date == Convert.ToDateTime(sDate))
                {
                    isbujia = true;
                }
            }
            return isbujia;
        }
        public static string GetHtmlFromUrl(string mt, string msg)
        {
            if (Config.debug)
                return string.Empty;
            string url = "http://www.jianzhou.sh.cn/JianzhouSMSWSServer/http/sendBatchMessage";
            string para = "account=sdk_wenshangdai&password=1582540&destmobile=" + mt + "&msgText=" + HttpUtility.UrlEncode(msg + "【温商贷】", Encoding.GetEncoding("utf-8")) + "&sendDateTime=";
            string strRet = "";
            try
            {
                WebRequest request = WebRequest.Create(url);
                request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                request.Method = "POST";
                request.Timeout = 25000;

                byte[] buf = Encoding.UTF8.GetBytes(para);
                request.ContentLength = buf.Length;
                Stream rStream = request.GetRequestStream();
                rStream.Write(buf, 0, buf.Length);
                rStream.Dispose();

                WebResponse response = request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    strRet = reader.ReadToEnd();
                }
                response.Close();
            }
            catch
            { }
            return strRet;
        }
        /// <summary>
        /// 聚益信息发送短信的方法
        /// </summary>
        /// <param name="mt">手机号码</param>
        /// <param name="msg">内容</param>
        /// <returns></returns>
        //public static string GetHtmlFromUrlJUYI(string mt, string msg)
        //{
        //    if (Config.debug)
        //        return string.Empty;
        //    string url = "http://121.199.28.96/stardy/send_jy.jsp";
        //    string strRet = "";
        //    //string para = "account=sdk_wenshangdai&password=1582540&destmobile=" + mt + "&msgText=" + HttpUtility.UrlEncode(msg + "【温商贷】", Encoding.GetEncoding("utf-8")) + "&sendDateTime=";
        //    try
        //    {
        //        int housi = 0;
        //        if (mt.Contains(","))
        //        {
        //            string fristmt = mt.Substring(0, mt.IndexOf(","));
        //            housi = Convert.ToInt32(fristmt.Substring(7, 4)) * 5 + 129;
        //        }
        //        else
        //        {
        //            housi = Convert.ToInt32(mt.Substring(7, 4)) * 5 + 129;
        //        }
        //        string para = "tjpc=1&usr=wsdai&pwd=wsdai8899&mobile=" + mt + "&msg=" + HttpUtility.UrlEncode(msg, Encoding.GetEncoding("gbk")) + "&yzm=" + housi;

        //        WebRequest request = WebRequest.Create(url);
        //        request.ContentType = "application/x-www-form-urlencoded;";
        //        request.Method = "POST";
        //        request.Timeout = 25000;

        //        byte[] buf = Encoding.UTF8.GetBytes(para);
        //        request.ContentLength = buf.Length;
        //        Stream rStream = request.GetRequestStream();
        //        rStream.Write(buf, 0, buf.Length);
        //        rStream.Dispose();

        //        WebResponse response = request.GetResponse();
        //        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GBK")))
        //        {
        //            strRet = reader.ReadToEnd();
        //        }
        //        response.Close();
        //    }
        //    catch
        //    { }
        //    return strRet;
        //}

        public static string GetHtmlFromUrlJUYI(string mt, string msg, string sms_type = "notice")
        {
            if (Config.debug) return string.Empty;
            string strRet = "";
            try
            {
                string url = "http://api.5iliulang.com/api/v1/manySend";
                string nonce_str = "wsdai01"; //短信平台用户名
                string app_key = "uwh2ulc2ay28v4mfvfxyncrahx9p4ntn";
                string app_secret = "1625db30fdb45e57c7e271956afee56f1171";
                string content = "【温商贷】" + msg;
                string batch_num = nonce_str + new Random().Next(100000, 999999);//批次号  考虑使用nonce_str+自然数若干位   //（ces001,测试发送时请更换，此处仅用于校对sgin）
                string time_stamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                string mission_num = "", dest_id = "", xmlstr = "";
                string[] mts = mt.Split(',');
                for (int i = 0; i < mts.Length; i++)
                {
                    dest_id += "&dest_id=" + mts[i];
                    mission_num += "&mission_num=w" + i.ToString();
                    xmlstr += "<dest><mission_num>w" + i.ToString() + "</mission_num><dest_id>" + mts[i] + "</dest_id></dest>";
                }
                string stringA = "app_key=" + app_key + "&batch_num=" + batch_num
                    + "&content=" + content + dest_id + mission_num
                    + "&nonce_str=" + nonce_str + "&sms_type=" + sms_type + "&time_stamp=" + time_stamp + "";
                string stringSignTemp = stringA + "&app_secret=" + app_secret + "";
                string sign = func.PassStr(stringSignTemp, "MD5");
                StringBuilder sb = new StringBuilder();
                sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                sb.Append("<xml><head>");
                sb.AppendFormat("<app_key>{0}</app_key>", app_key);
                sb.AppendFormat("<time_stamp>{0}</time_stamp>", time_stamp);
                sb.AppendFormat("<nonce_str>{0}</nonce_str>", nonce_str);
                sb.AppendFormat("<sign>{0}</sign>", sign);
                sb.Append("</head><body><dests>");
                sb.Append(xmlstr);
                sb.Append("</dests>");
                sb.AppendFormat("<batch_num>{0}</batch_num>", batch_num);
                sb.AppendFormat("<sms_type>{0}</sms_type>", sms_type);
                sb.AppendFormat("<content>{0}</content>", content);
                sb.Append("</body></xml>");
                string para = sb.ToString();

                WebRequest request = WebRequest.Create(url);
                request.ContentType = "application/x-www-form-urlencoded;";
                request.Method = "POST";
                request.Timeout = 25000;

                byte[] buf = Encoding.UTF8.GetBytes(para);
                request.ContentLength = buf.Length;
                Stream rStream = request.GetRequestStream();
                rStream.Write(buf, 0, buf.Length);
                rStream.Dispose();

                WebResponse response = request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8")))
                {
                    strRet = reader.ReadToEnd();
                }
                response.Close();
            }
            catch (Exception ex) { strRet = ex.Message; }
            return strRet;
        }


        /// <summary>
        /// 云通讯语音验证码
        /// </summary>
        /// <param name="to">接收号码</param>
        /// <param name="verifyCode">验证码内容，为数字和英文字母，不区分大小写，长度4-8位</param>
        /// <param name="displayNum">可选字段 显示主叫号码，显示权限由服务侧控制（该参数已无效）</param>
        /// <param name="playTimes">可选字段 循环播放次数，1－3次，默认播放1次</param>
        /// <param name="respUrl">可选字段 语音验证码状态通知回调地址，云通讯平台将向该Url地址发送呼叫结果通知</param>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        /// <exception cref="Exception"></exception>
        /// <returns></returns>
        //public static string VoiceVerify(string m_appId, string to, string verifyCode, string displayNum, string playTimes, string respUrl, int flx=1)
        //{
        //    string ip = func.GetIP();
        //    if (db3.ExecInt(string.Format("select count(id) from t_VoiceRequest where datediff(minute,tdate,getdate())=0 and flx={0} and cip='{1}'", flx, ip))<5)
        //    {
        //        db3.ExecNQ(string.Format("insert into t_VoiceRequest(tel,cip,flx) values('{0}','{1}',{2})", to, ip, flx));
        //    }
        //    else
        //    {
        //        return "1";
        //    }

        //    string m_mainAccount = "8a48b55152f2357c0152f30310a50244";
        //    string m_mainToken = "fdb2805d9e414e2d8a2357299823266d";
        //    string m_restAddress = "app.cloopen.com";//sandboxapp.cloopen.com(测试)
        //    string m_restPort = "8883";
        //    string softVer = "2013-12-26";// 服务器api版本
        //    try
        //    {
        //        string date = DateTime.Now.ToString("yyyyMMddhhmmss");

        //        // 构建URL内容
        //        string sigstr = func.PassStr(m_mainAccount + m_mainToken + date, "MD5");
        //        string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/Calls/VoiceVerify?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr);
        //        Uri address = new Uri(uriStr);

        //        // 创建网络请求  
        //        HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
        //        setCertificateValidationCallBack();

        //        // 构建Head
        //        request.Method = "POST";

        //        Encoding myEncoding = Encoding.GetEncoding("utf-8");
        //        byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
        //        string authStr = Convert.ToBase64String(myByte);
        //        request.Headers.Add("Authorization", authStr);


        //        // 构建Body
        //        StringBuilder data = new StringBuilder();

        //        request.Accept = "application/json";
        //        request.ContentType = "application/json;charset=utf-8";

        //        data.Append("{");
        //        data.Append("\"to\":\"").Append(to).Append("\"");
        //        data.Append(",\"appId\":\"").Append(m_appId).Append("\"");
        //        data.Append(",\"verifyCode\":\"").Append(verifyCode).Append("\"");

        //        if (displayNum != null)
        //        {
        //            data.Append(",\"displayNum\":\"").Append(displayNum).Append("\"");
        //        }

        //        if (playTimes != null)
        //        {
        //            data.Append(",\"playTimes\":\"").Append(playTimes).Append("\"");
        //        }

        //        if (respUrl != null)
        //        {
        //            data.Append(",\"respUrl\":\"").Append(respUrl).Append("\"");
        //        }

        //        data.Append("}");



        //        byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

        //        // 开始请求
        //        using (Stream postStream = request.GetRequestStream())
        //        {
        //            postStream.Write(byteData, 0, byteData.Length);
        //        }

        //        // 获取请求
        //        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        //        {
        //            // Get the response stream  
        //            StreamReader reader = new StreamReader(response.GetResponseStream());
        //            string responseStr = reader.ReadToEnd();

        //            if (responseStr != null && responseStr.Length > 0)
        //            {
        //                return responseStr;
        //            }
        //            return "{ \"statusCode\", 172002 ,\"statusMsg\", \"无返回\" , \"data\", null }";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        return "{ \"statusCode\", 172003 ,\"statusMsg\", \"" + ex + "\" , \"data\", null }";
        //    }
        //}

        /// <summary>
        /// 设置服务器证书验证回调
        /// </summary>
        public static void setCertificateValidationCallBack()
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback = CertificateValidationResult;
        }

        /// <summary>
        ///  证书验证回调函数  
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cer"></param>
        /// <param name="chain"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool CertificateValidationResult(object obj, System.Security.Cryptography.X509Certificates.X509Certificate cer, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors error)
        {
            return true;
        }

        /// <summary>
        /// 阿里大鱼发送信息专用
        /// </summary>
        /// <param name="mt">手机号码</param>
        /// <param name="msgname">变量名称</param>
        /// <param name="msgvalue">变量内容</param>
        /// <param name="xxTempCode">
        /// 信息模板编码
        /// 1，SMS_350011 为发送验证码的模板，名称为code,值为验证码。
        /// 2，SMS_350013 为充值成功验证码，名称 username 值为用户名。
        /// 3，SMS_360021 为满标审核模板，发给投资用户的，名称为datetime，值为满标时间
        /// 4，SMS_350014 为满标审核发给借款人的模板，名为datetime,值为满标时间
        /// 5，SMS_350015 为回款模板，名为datetime，值为回款时间
        /// </param>
        /// <returns></returns>
        //public static bool GetHtmlFromUrl(string mt, string msgname, string msgvalue, string xxTempCode)
        //{
        //    bool bIsSuccess = false;
        //    try
        //    {
        //        ITopClient client = new DefaultTopClient("http://gw.api.tbsandbox.com/router/rest", "1023240425", "sandboxfb565d8abe5643ce0b4c37f22");
        //        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        //        req.Extend = "";
        //        req.SmsType = "normal";
        //        req.SmsFreeSignName = "wsloan";
        //        req.SmsParam = "{\"" + msgname + "\":\"" + msgvalue + "\"}";
        //        req.RecNum = mt;
        //        req.SmsTemplateCode = xxTempCode;
        //        AlibabaAliqinFcSmsNumSendResponse response = client.Execute(req, "");
        //        bIsSuccess = true;
        //    }
        //    catch
        //    {
        //    }
        //    return bIsSuccess;
        //}
        public static string GetSqlstr(int PgIndex, int PgSize, string Allfd, string Tabwhere, string Orderfd)
        {
            //if (PgIndex > 10) PgIndex = 10;
            string sql;
            if (PgIndex == 1)
            {
                sql = "select top " + PgSize + " " + Allfd + " from " + Tabwhere + " " + Orderfd;
            }
            else
            {
                int qs = PgSize * (PgIndex - 1) + 1;
                sql = "select * from (select row_number() over (" + Orderfd + ") as ipx," + Allfd + " from " + Tabwhere + ") t_0 where ipx between ";
                sql += qs.ToString() + " and " + (PgSize * PgIndex).ToString();
            }
            return sql;
        }

        public static string pager(int dqpg, int zjls, string url) //当前页码,当前页的记录数,后缀参数
        {
            string str = "第" + dqpg + "页&nbsp;";
            if (dqpg > 1)
                str += "<a href=?page=1" + url + ">首页</a>&nbsp;<a href=?page=" + (dqpg - 1) + url + ">上页</a>&nbsp;";
            else
                str += "<span>首页</span>&nbsp;<span>上页</span>&nbsp;";
            if (zjls > 0)
                str += "<a href=?page=" + (dqpg + 1) + url + ">下页</a>";
            else
                str += "<span>下页</span>";
            str += "&nbsp;到第<input name=\"page\" type=\"text\" id=\"page\" style=\"width:30px\" onKeyUp=\"value=value.replace(/[^0123456789]/g,'')\">页&nbsp;<input type=\"button\" name=\"Submit\" value=\"GO\" onClick=\"topage()\">\n<script type=\"text/JavaScript\">\nfunction topage(){\nvar pg=document.getElementById(\"page\").value;\nlocation.href=\"?page=\"+pg+\"" + url + "\"}\n</script>";
            return str;
        }



        #region 活期会员中心输出分页栏
        /// <summary>
        /// 活期会员中心输出分页栏
        /// </summary>
        /// <param name="PageIndex">当前页码</param>
        /// <param name="Querry">其它Querry参数</param>
        /// <param name="PageCount">总页数</param>
        /// <returns></returns>
        public static string PagerHtml(int PageIndex, string Querry, int PageCount)
        {
            if (PageCount < 2)
            {
                return "";
            }

            if (PageIndex < 1)
            {
                PageIndex = 1;
            }

            if (PageIndex > PageCount)
            {
                PageIndex = PageCount;
            }

            int PageNext = PageIndex + 1;

            string PageHtml = @"
                <div class=""page_ct""><p>
                    [FirestHtml]&nbsp;
                    [PrvHtml]&nbsp;
                    [NextHtml]&nbsp;
                    [LastHtml]&nbsp;
                    共<b>[PageCount]</b>页
                    当前第<b>[PageIndex]</b>页
                    到第<input name=""page"" type=""text"" id=""page"" style=""width: 30px"" onkeyup=""value = value.replace(/[^ 0123456789] / g, '')"">页&nbsp;<input type=""button"" name=""Submit"" value=""GO"" onclick=""topage()"">

                    [toPageJS]&nbsp;
                </p></div>";

            string toPageJS = "";
            string FirestHtml = "";
            string PrvHtml = "";
            string NextHtml = "";
            string LastHtml = "";
            toPageJS = "<script type = \"text/JavaScript\">" +
                    " function topage() {" +
                            "var pg = document.getElementById(\"page\").value;" +
                            "var pageindex;" +
                            "if(pg<1){pageindex=1}" +
                            "else if(pg>" + PageCount + "){pageindex=" + PageCount + "}" +
                            "else{pageindex=pg}" +
                            "if(\"" + string.IsNullOrWhiteSpace(Querry) + "\"==\"False\"){location.href = \"?page=\" + pageindex + \"&" + Querry + "\"}" +
                            "else{location.href = \"?page=\" + pageindex }" +
                    "}</script>";

            if (PageIndex == 1)
            {
                FirestHtml = "<span>首页</span>";
                PrvHtml = "<span>上页</span>";
            }
            else
            {
                FirestHtml = "<a href=\"?page=1&" + Querry + "\">首页</a>";
                PrvHtml = "<a href=\"?page=" + (PageIndex - 1) + "&" + Querry + "\">上页</a>";
            }

            if (PageIndex == PageCount)
            {
                NextHtml = "<span>下页</span>";
                LastHtml = "<span>末页</span>";
            }
            else
            {
                NextHtml = "<a href=\"?page=" + (PageIndex + 1) + "&" + Querry + "\">下页</a>";
                LastHtml = "<a href=\"?page=" + PageCount + "&" + Querry + "\">末页</a>";
            }

            return PageHtml.Replace("[FirestHtml]", FirestHtml).Replace("[PrvHtml]", PrvHtml).Replace("[NextHtml]", NextHtml).Replace("[LastHtml]", LastHtml).Replace("[toPageJS]", toPageJS).Replace("[PageCount]", PageCount.ToString()).Replace("[PageIndex]", PageIndex.ToString());
        }
        #endregion


    }

    public class txzc
    {
        private string dyid;

        public string Dyid
        {
            get { return dyid; }
            set { dyid = value; }
        }
        private decimal ye;

        public decimal Ye
        {
            get { return ye; }
            set { ye = value; }
        }
        private decimal czje;

        public decimal Czje
        {
            get { return czje; }
            set { czje = value; }
        }
        private decimal jl;

        public decimal Jl
        {
            get { return jl; }
            set { jl = value; }
        }

        private decimal hkje;

        public decimal Hkje
        {
            get { return hkje; }
            set { hkje = value; }
        }
    }
}